<template>
  <div>
    <div style="padding: 20px; background-color: rgba(140,147,157,0)">
      <el-checkbox v-model="selectAll" @change="toggleSelectAll" style="margin: 10px">全选</el-checkbox>
      <el-button @click="downloadSelected">下载选中图片</el-button>
      <el-button @click="clean">清除数据</el-button>
      <el-button @click="goBack">返回上一级</el-button>
    </div>
    <br>
    <div v-for="(item, index) in urls" :key="index" style="display: inline-block; margin: 10px;">
      <el-checkbox v-model="selectedUrls" :label="item.url">
        <br>
      </el-checkbox>
      <el-image
          style="width: 100px; height: 100px"
          :src="item.url"
          :preview-src-list="urls.map(urlItem => urlItem.url)"
          :preview-teleported="true"
          :initial-index="index"
      />
    </div>
  </div>
</template>

<script lang="ts" setup>
import {ref, onMounted, computed, onBeforeUnmount, onUnmounted, watch, reactive} from 'vue'
import {useRoute, useRouter} from 'vue-router'
import {ElButton, ElImage} from 'element-plus'
import {createCanvas, loadImage} from 'canvas';
import axiosInstance from "@/utils/axios";
import {useStore} from "vuex";

const store = useStore();

const route = useRoute()
const router = useRouter() // 初始化路由

const value0 = ref('')
const value2 = ref('')
const template = ref('')
const inputs = ref([])
const keywords = ref([])
const urls = ref([])
const selectedUrls = ref<string[]>([]) // 修改为string[]以存储url字符串

// 添加: selectAll 变量和 toggleSelectAll 方法
const selectAll = ref(false)

const toggleSelectAll = () => {
  if (selectAll.value) {
    selectedUrls.value = urls.value.map(urlItem => urlItem.url) // 修改为存储url字符串
  } else {
    selectedUrls.value = []
  }
}

function generateCombinations(arr, template) {
  const results = [];

  function recurse(current, index) {
    if (index === arr.length) {
      results.push(template.replace(/\{(\d+)\}/g, (match, p1) => current[p1]));
      return;
    }

    for (let i = 0; i < arr[index].length; i++) {
      recurse(current.concat(arr[index][i]), index + 1);
    }
  }

  recurse([], 0);
  return results;
}

let isRunning = true;

const sendTask = (resultPrompt: string[]) => {
    let index = 0;
    let attempt = 0;

    const sendRequest = () => {
      if (!isRunning) return; // 新增: 检查标志变量，如果为 false 则停止递归
      if (index >= resultPrompt.length) {
        index = 0
      }

      const obj = {english: resultPrompt[index]};
      const json_data = {
        'base64Array': [],
        'notifyHook': '',
        'prompt': obj.english,
        'state': '',
      };

      axiosInstance.post('/submit/imagine', json_data)
          .then(response => {
            console.log('submit!', response.data);
            if (response.data.result !== null) {
              store.commit('appendImageCode', {new: [response.data.result], old: []});
            }
            console.log(store.state.imageCode)
            attempt = 0; // 重置尝试次数
            index++;
            setTimeout(() => sendRequest(), 3000);
          })
          .catch(error => {
            console.error('error submit!', error);
            attempt++;
            if (attempt < 2) {
              setTimeout(() => sendRequest(), 3000);
            } else {
              attempt = 0; // 重置尝试次数
              index++;
              setTimeout(() => sendRequest(), 3000);
            }
          });
    };

    sendRequest();
};

// 添加: 定时器相关变量
let fetchInterval: NodeJS.Timeout | null = null

const fetchTaskList = async () => {
  try {
    let ids = [...store.state.imageCode.new]
    await axiosInstance.post('task/list-by-condition', {
      'ids': ids
    }).then(response => {
      for (let i = 0; i < response.data.length; i++) {
        let scopeParam = response.data[i];
        if (scopeParam.status === 'SUCCESS' && scopeParam.action === 'IMAGINE') {
          let index = store.state.imageCode.new.indexOf(scopeParam.id);
          if (index !== -1) {
            store.commit('appendImageCode', {
              new: [],
              old: [scopeParam.id]
            });
            store.commit('removeImageCode', {
              new: [scopeParam.id],
              old: []
            });


            let urlParams = [{"url": scopeParam.imageUrl, "prompt": scopeParam.prompt}]
            axiosInstance.post('/submit/download-and-zip', urlParams, { responseType: 'blob' })
                .then(response => {

                })
                .catch(error => {
                  console.error('Error downloading and zipping images:', error);
                });
          }
          // 新增: 将scopeParam里面的imageUrl放入到urls对象里面

          if (scopeParam.imageUrl) {
            // 这里 要校验URl是否在urls里面
            urls.value.push({
              url: scopeParam.imageUrl,
              index: urls.value.length
            });
          }
          console.log(store.state.imageCode)
        }
      }
    }).catch(error => {
      console.error('error submit!', error);
    });
  } catch (error) {
    console.error('Error fetching task list:', error);
  }
};

let intervalId = null;

onMounted(() => {
  value0.value = route.query.value0 as string
  value2.value = route.query.value2 as string
  template.value = route.query.template as string
  inputs.value = route.query.inputs as string[]
  console.log('Value0:', value0.value)
  console.log('Value2:', value2.value)
  console.log('inputs:', inputs.value)
  console.log('template:', template.value)
  let value2Parts = inputs.value.map((item, index) => {
    return item.split(',')
  })
  let resultPrompt = generateCombinations(value2Parts, template.value)

  console.log(resultPrompt)

  sendTask(resultPrompt)

  intervalId = setInterval(() => {
    fetchTaskList();
  }, 3000);

})

onUnmounted(() => {
  // 清除定时器
  if (intervalId) {
    clearInterval(intervalId);
  }
});

onBeforeUnmount(() => {
  // 清除定时器
  if (fetchInterval) {
    clearInterval(fetchInterval)
  }
})

const clean = () => {
  isRunning = false
  store.commit('removeImageCode', {new: [], old: []});
  router.push({name: 'dataSet'});
}

const goBack = () => {
  // 清除定时器
  isRunning = false
  store.commit('removeImageCode', {new: [], old: []});
  clearInterval(intervalId);
  router.go(-1);
}

const downloadSelected = () => {
  console.log(selectedUrls);
  axiosInstance.post('/submit/download-and-zip', selectedUrls.value, { responseType: 'blob' })
      .then(response => {
        const url = window.URL.createObjectURL(response.data);
        const link = document.createElement('a');
        link.href = url;
        link.download = 'images.zip';  // 可以修改为动态文件名
        document.body.appendChild(link);
        link.click();
        document.body.removeChild(link);
        window.URL.revokeObjectURL(url);
      })
      .catch(error => {
        console.error('Error downloading and zipping images:', error);
      });
}



</script>

<style scoped>

</style>